package apis

import (
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"go-admin/app/admin/models"
	"go-admin/common/auth/member"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
	"github.com/golang/glog"
	"github.com/google/uuid"
	"go-admin/app/admin/service"
	"go-admin/app/admin/service/dto"
	"go-admin/common/actions"
)

type SysMember struct {
	api.Api
}

// GetPage
// @Summary 列表会员信息数据
// @Description 获取JSON
// @Tags 会员
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-member [get]
// @Security Bearer
func (e SysMember) GetPage(c *gin.Context) {
	s := service.SysMember{}
	req := dto.SysMemberGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysMember, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Get
// @Summary 获取会员
// @Description 获取JSON
// @Tags 会员
// @Param memberId path int true "会员编码"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-member/{memberId} [get]
// @Security Bearer
func (e SysMember) Get(c *gin.Context) {
	glog.Info("----------")

	s := service.SysMember{}
	req := dto.SysMemberById{}
	glog.Info(req.GetId())
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object models.SysMember
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, "查询失败")
		return
	}
	e.OK(object, "查询成功")
}

// Insert
// @Summary 创建会员
// @Description 获取JSON
// @Tags 会员
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysMemberInsertReq true "会员数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-member [post]
// @Security Bearer
func (e SysMember) Insert(c *gin.Context) {
	s := service.SysMember{}
	req := dto.SysMemberInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c))
	err = s.Insert(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// Update
// @Summary 修改会员数据
// @Description 获取JSON
// @Tags 会员
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysMemberUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-member/{memberId} [put]
// @Security Bearer
func (e SysMember) Update(c *gin.Context) {
	s := service.SysMember{}
	req := dto.SysMemberUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	req.SetUpdateBy(user.GetUserId(c))

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.Update(&req, p)
	if err != nil {
		e.Logger.Error(err)
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete
// @Summary 删除会员数据
// @Description 删除数据
// @Tags 会员
// @Param memberId path int true "memberId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-member/{memberId} [delete]
// @Security Bearer
func (e SysMember) Delete(c *gin.Context) {
	s := service.SysMember{}
	req := dto.SysMemberById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// 设置编辑人
	req.SetUpdateBy(user.GetUserId(c))

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Logger.Error(err)
		return
	}
	e.OK(req.GetId(), "删除成功")
}

// InsetAvatar
// @Summary 修改头像
// @Description 获取JSON
// @Tags 个人中心
// @Accept multipart/form-data
// @Param file formData file true "file"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/member/avatar [post]
// @Security Bearer
func (e SysMember) InsetAvatar(c *gin.Context) {
	s := service.SysMember{}
	req := dto.UpdateSysMemberAvatarReq{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 数据权限检查
	p := actions.GetPermissionFromContext(c)
	form, _ := c.MultipartForm()
	files := form.File["upload[]"]
	guid := uuid.New().String()
	filPath := "static/uploadfile/" + guid + ".jpg"
	for _, file := range files {
		e.Logger.Debugf("upload avatar file: %s", file.Filename)
		// 上传文件至指定目录
		err = c.SaveUploadedFile(file, filPath)
		if err != nil {
			e.Logger.Errorf("save file error, %s", err.Error())
			e.Error(500, err, "")
			return
		}
	}
	req.Avatar = "/" + filPath

	err = s.UpdateAvatar(&req, p)
	if err != nil {
		e.Logger.Error(err)
		return
	}
	e.OK(filPath, "修改成功")
}

// UpdateStatus 修改会员状态
// @Summary 修改会员状态
// @Description 获取JSON
// @Tags 会员
// @Accept  application/json
// @Product application/json
// @Param data body dto.UpdateSysMemberStatusReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/member/status [put]
// @Security Bearer
func (e SysMember) UpdateStatus(c *gin.Context) {
	s := service.SysMember{}
	req := dto.UpdateSysMemberStatusReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	req.SetUpdateBy(user.GetUserId(c))

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.UpdateStatus(&req, p)
	if err != nil {
		e.Logger.Error(err)
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// ResetPwd 重置会员密码
// @Summary 重置会员密码
// @Description 获取JSON
// @Tags 会员
// @Accept  application/json
// @Product application/json
// @Param data body dto.ResetSysMemberPwdReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/member/pwd/reset [put]
// @Security Bearer
func (e SysMember) ResetPwd(c *gin.Context) {
	s := service.SysMember{}
	req := dto.ResetSysMemberPwdReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	req.SetUpdateBy(user.GetUserId(c))

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.ResetPwd(&req, p)
	if err != nil {
		e.Logger.Error(err)
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// UpdatePwd
// @Summary 重置密码
// @Description 获取JSON
// @Tags 会员
// @Accept  application/json
// @Product application/json
// @Param data body dto.MemberPassWord true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/member/pwd/set [put]
// @Security Bearer
func (e SysMember) UpdatePwd(c *gin.Context) {
	s := service.SysMember{}
	req := dto.MemberPassWord{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.UpdatePwd(member.GetMemberId(c), req.OldPassword, req.NewPassword, p)
	if err != nil {
		e.Logger.Error(err)
		e.Error(http.StatusForbidden, err, "密码修改失败")
		return
	}
	e.OK(nil, "密码修改成功")
}

// GetProfile
// @Summary 获取个人中心会员
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/member/profile [get]
// @Security Bearer
func (e SysMember) GetProfile(c *gin.Context) {
	s := service.SysMember{}
	req := dto.SysMemberById{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	req.Id = member.GetMemberId(c)

	sysMember := models.SysMember{}
	roles := make([]models.SysRole, 0)
	posts := make([]models.SysPost, 0)
	err = s.GetProfile(&req, &sysMember, &roles, &posts)
	if err != nil {
		e.Logger.Errorf("get member profile error, %s", err.Error())
		e.Error(500, err, "获取会员信息失败")
		return
	}
	e.OK(gin.H{
		"member": sysMember,
		"roles":  roles,
		"posts":  posts,
	}, "查询成功")
}

// GetInfo
// @Summary 获取个人信息
// @Description 获取JSON
// @Tags 个人中心
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/getmemberinfo [get]
// @Security Bearer
func (e SysMember) GetInfo(c *gin.Context) {
	req := dto.SysMemberById{}
	s := service.SysMember{}
	r := service.SysRole{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&r.Service).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	p := actions.GetPermissionFromContext(c)
	var permissions = make([]string, 1)
	permissions[0] = "*:*:*"
	var buttons = make([]string, 1)
	buttons[0] = "*:*:*"

	var mp = make(map[string]interface{})
	sysMember := models.SysMember{}
	req.Id = member.GetMemberId(c)
	err = s.Get(&req, p, &sysMember)
	if err != nil {
		e.Error(http.StatusUnauthorized, err, "登录失败")
		return
	}
	mp["introduction"] = " am a VIP"
	mp["avatar"] = ""
	if sysMember.Avatar != "" {
		mp["avatar"] = sysMember.Avatar
	}
	mp["userName"] = sysMember.NickName
	mp["id"] = sysMember.Id
	mp["name"] = sysMember.NickName
	mp["code"] = 200
	e.OK(mp, "")
}
